package com.tsinghuabigdata.edu.ddmath.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.adapter.PreviewPageAdapter;
import com.tsinghuabigdata.edu.ddmath.adapter.PreviewThumbAdapter;
import com.tsinghuabigdata.edu.ddmath.inter.MyItemClickListener;
import com.tsinghuabigdata.edu.ddmath.util.DensityUtils;
import com.tsinghuabigdata.edu.ddmath.util.WindowUtils;

import java.util.ArrayList;


/**
 * 照片大图预览界面
 * Created by Administrator on 2017/2/17.
 */

public class PicturePreviewActivity extends RoboActivity implements MyItemClickListener {

    //上传时间
    public static final String PARMA_TIME   = "time";
    //多个图片地址，用","分割
    public static final String PARMA_IMAGES = "imagespath";
    public static final String PARMA_CORRECT= "correctinfos";
    //显示的是第几张图片
    public static final String PARMA_INDEX  = "showindex";


    private PreviewThumbAdapter mPreviewThumbAdapter;

    private ImageView    mIvBack;
    private TextView     mTvBack;
    private TextView     mTvTitle;
    private ViewPager    mViewPager;
    private RecyclerView mRvPreview;
    private int          mScreenWidth;
    private int          mSingleWidth;
    private int          mContentWidth;
    private int          totalDx;

    /**
     * 启动图片预览
     *
     * @param context 上下文
     * @param images  //多个图片地址，用","分割, 网络图片是完整的url
     * @param index   //当前显示的序号
     */
    public static void startPicturePreviewActivity(Context context, String images, int index, String uploadTime) {
        Intent intent = new Intent(context, PicturePreviewActivity.class);
        intent.putExtra(PicturePreviewActivity.PARMA_IMAGES, images);
        intent.putExtra(PicturePreviewActivity.PARMA_INDEX, index);
        if (!TextUtils.isEmpty(uploadTime))
            intent.putExtra(PicturePreviewActivity.PARMA_TIME, uploadTime);
        context.startActivity(intent);
    }
    public static void startPicturePreviewActivity(Context context, String images, String corrects, int index, String uploadTime) {
        Intent intent = new Intent(context, PicturePreviewActivity.class);
        intent.putExtra(PicturePreviewActivity.PARMA_IMAGES, images);
        intent.putExtra(PicturePreviewActivity.PARMA_INDEX, index);
        if (!TextUtils.isEmpty(uploadTime))
            intent.putExtra(PicturePreviewActivity.PARMA_TIME, uploadTime);
        intent.putExtra(PicturePreviewActivity.PARMA_CORRECT, corrects);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture_preview);
        initView();
        initData();
    }

    private void initView() {
        mIvBack = (ImageView) findViewById(R.id.iv_back);
        mTvBack = (TextView) findViewById(R.id.tv_back);
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        mRvPreview = (RecyclerView) findViewById(R.id.rv_preview);
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        };
        mIvBack.setOnClickListener(listener);
        mTvBack.setOnClickListener(listener);
    }

    private void initData() {
        String images = getIntent().getStringExtra(PARMA_IMAGES);
        final int index = getIntent().getIntExtra(PARMA_INDEX, 0);
        String time = getIntent().getStringExtra(PARMA_TIME);
        String corrects = getIntent().getStringExtra( PARMA_CORRECT );

        ArrayList<String> correctInfos = null;
        if( !TextUtils.isEmpty( corrects ) ){
            String[] array = corrects.split("#");
            correctInfos = new ArrayList<>();
            for(String str : array ){
                correctInfos.add( str );
            }
        }

        if (!TextUtils.isEmpty(time) && time.length() > 16) {
            String minute = time.substring(11, 16);
            mTvTitle.setText(minute + " 上传");
        }
        String[] urlArray = images.split(",");
        int size = urlArray.length;
        mScreenWidth = WindowUtils.getScreenWidth(this);
        mSingleWidth = DensityUtils.dp2px(this, 92);
        mContentWidth = DensityUtils.dp2px(this, 92 * size);
        if (mContentWidth < mScreenWidth) {
            int marginWidth = mScreenWidth - mContentWidth;
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mRvPreview.getLayoutParams();
            layoutParams.leftMargin = marginWidth / 2;
            mRvPreview.setLayoutParams(layoutParams);
        }
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < size; i++) {
            list.add(urlArray[i]);
        }
        PreviewPageAdapter previewPageAdapter = new PreviewPageAdapter(this, list);
        previewPageAdapter.setActivity( this );
        previewPageAdapter.setCorrectInfo(  correctInfos );
//        mViewPager.setOffscreenPageLimit(size);

        mViewPager.setAdapter(previewPageAdapter);
        mViewPager.setCurrentItem(index);
        mPreviewThumbAdapter = new PreviewThumbAdapter(this, list, index);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRvPreview.setLayoutManager(layoutManager);
        mRvPreview.setAdapter(mPreviewThumbAdapter);
        mPreviewThumbAdapter.setOnItemClickListener(this);
        mRvPreview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                totalDx -= dx;
                Log.i("sky", "onScrolled totalDx=" + totalDx);
            }
        });
        mRvPreview.postDelayed(new Runnable() {
            @Override
            public void run() {
                scroll(index);
            }
        }, 100);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mPreviewThumbAdapter.select(position);
                scroll(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void scroll(int position) {
        int dis = (int) ((position + 0.5) * mSingleWidth) - mScreenWidth / 2;
        //        int extraDis = mContentWidth - mScreenWidth;
        //        if (dis < 0) {
        //            dis = 0;
        //        }
        //        if (dis > extraDis) {
        //            dis = extraDis;
        //        }
        Log.i("sky", "totalDx=" + totalDx + "dis=" + dis);
        mRvPreview.scrollBy(dis + totalDx, 0);
    }

    @Override
    public void onItemClick(View view, int position) {
        mPreviewThumbAdapter.select(position);
        mViewPager.setCurrentItem(position, false);
        scroll(position);
    }

    public void updateImage(final ImageView imageView, final Bitmap bitmap ){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                imageView.setImageBitmap( bitmap );
            }
        });
    }
}
